package com.veinhorn.scrollgalleryview.loader;

import com.veinhorn.scrollgalleryview.Constants;
import com.veinhorn.scrollgalleryview.util.LogUtil;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Image;
import ohos.agp.components.element.PixelMapElement;
import ohos.app.Context;
import ohos.global.resource.NotExistException;
import ohos.global.resource.Resource;

import java.io.IOException;

/**
 * DefaultVideoLoader
 *
 * @author Alexey Nevinsky
 * @since 2021-05-13
 */
public class DefaultVideoLoader implements MediaLoader {
    private String mUrl;
    private int mId;
    private PixelMapElement mBitmap;

    /**
     * DefaultVideoLoader
     *
     * @param url
     * @param id
     */
    public DefaultVideoLoader(String url, int id) {
        this.mUrl = url;
        this.mId = id;
    }

    /**
     * isImage
     *
     * @return boolean
     */
    @Override
    public boolean isImage() {
        return false;
    }

    /**
     * loadMedia
     *
     * @param context
     * @param imageView
     * @param callback
     */
    @Override
    public void loadMedia(final Context context, Image imageView, SuccessCallback callback) {
        loadBitmap(context);

        imageView.setPixelMap(mId);
        imageView.setClickedListener(view -> {
            displayVideo(context, mUrl);
        });
    }

    /**
     * loadThumbnail
     *
     * @param context
     * @param thumbnailView
     * @param callback
     */
    @Override
    public void loadThumbnail(Context context, Image thumbnailView, SuccessCallback callback) {
        loadBitmap(context);
        thumbnailView.setImageElement(mBitmap);
        callback.onSuccess();
    }

    /**
     * 视频跳转到视频播放界面
     *
     * @param context
     * @param url
     */
    private void displayVideo(Context context, String url) {
        Operation operation = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName("com.veinhorn.scrollgalleryview.example.builder")
                .withAbilityName("com.veinhorn.scrollgalleryview.VideoPlayerAbility")
                .build();
        Intent intent = new Intent();
        intent.setParam(Constants.STR_VIDEOURL, url);
        intent.setOperation(operation);
        context.startAbility(intent, 1);
    }

    private void loadBitmap(Context context) {
        if (mBitmap == null) {
            Resource bgResource = null;
            try {
                bgResource = context.getResourceManager().getResource(mId);
                PixelMapElement pixBg = new PixelMapElement(bgResource);
                mBitmap = pixBg;
            } catch (IOException e) {
                LogUtil.error("DefaultVideoLoader-IOException",e.getMessage());
            } catch (NotExistException e) {
                LogUtil.error("DefaultVideoLoader-NotExistException",e.getMessage());
            }
        }
    }
}
